package com.bijiawang.user.service;

import com.bijiawang.user.bean.Userinfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserinfoService userinfoService;

    /**
     * 没勾选记住我，单纯登录，直接执行一次该方法，获取即输入的手机号
     * 勾选记住我，会执行两次该方法，第一次认证，第二次记住我
     *
     * @param phone1AndName2 第一次的参数为手机号，第二次的参数为用户名
     * @return 返回封装好的User提供认证
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String phone1AndName2) throws UsernameNotFoundException {
        Userinfo userinfoByPhoneNumber = userinfoService.getUserinfoByPhoneNumber(phone1AndName2);
        if (userinfoByPhoneNumber == null) {//用户第一次执行是认证，第二次执行是记住我
            Userinfo userinfoByUserName = userinfoService.getUserinfoByUserName(phone1AndName2);
            if(userinfoByUserName==null){
                throw new UsernameNotFoundException("当前用户不存在！");
            }
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(userinfoByUserName.getAuthority());
            List<SimpleGrantedAuthority> list = Collections.singletonList(simpleGrantedAuthority);
            User user = new User(userinfoByUserName.getUsername(), userinfoByUserName.getPassw(), list);
            return user;
        }
        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(userinfoByPhoneNumber.getAuthority());
        List<SimpleGrantedAuthority> list = Collections.singletonList(simpleGrantedAuthority);
        User user = new User(userinfoByPhoneNumber.getUsername(), userinfoByPhoneNumber.getPassw(), list);
        return user;
    }
}
